<template>
    <article>
        <el-drawer v-model="visable" size="800px" class="select-colunm-dialog" destroy-on-close @close="handleClose">
            <template #header>
                <div>
                    <span class="select-dialog-title">{{ props.title }}</span>
                    <el-tooltip v-if="slots.description" effect="dark" :placement="props.placement">
                        <template #content>
                            <slot name="description"></slot>
                        </template>
                        <span class="select-dialog-icon">
                            <el-icon color="#ccc" size="16"><QuestionFilled /></el-icon>
                        </span>
                    </el-tooltip>
                </div>
            </template>
            <el-row v-loading="loading">
                <div class="dialog-body zw-common-scrollbar">
                    <span>可勾选{{ length }}个常用指标在统计页面进行展示</span>
                    <el-checkbox-group
                        v-model="checkColumnsList"
                        class="column-list"
                        :max="checkColumnsList.length > length ? undefined : length"
                        :class="{ 'short-height': isNotAddData }">
                        <label
                            v-for="item in columnsList"
                            :key="item.field_key"
                            class="column-card"
                            @click="checkIsOverFlow(item)"
                            @mouseleave="item.overflowVisable = false">
                            <div class="column-card-title">
                                <div>{{ item.field_name }}</div>
                                <el-tooltip :visible="Boolean(item.overflowVisable)" placement="top-end">
                                    <template #content>
                                        {{ `仅能选择${props.length}个常用指标` }}
                                    </template>
                                    <el-checkbox :disabled="computedIsDisabled(item)" :label="item.field_key" />
                                </el-tooltip>
                            </div>
                            <div class="column-card-num">
                                <render-colunm-number :num="item.field_val" :unit="item.unit" />
                            </div>
                            <div v-if="props.type == 8" class="column-card-add">
                                <span>昨日: </span>
                                <span class="column-card-add">{{ item.yesterday }}</span>
                            </div>
                            <div v-else-if="item.today || item.today === 0" class="column-card-add">
                                <span>今日新增: </span>
                                <span class="column-card-add">{{ item.today }}</span>
                            </div>
                        </label>
                    </el-checkbox-group>
                </div>
            </el-row>
            <template #footer>
                <span class="dialog-footer">
                    <el-button :loading="buttonLoading" @click="visable = false">取消</el-button>
                    <el-button :loading="buttonLoading" type="primary" @click="submit">确认</el-button>
                </span>
            </template>
        </el-drawer>
    </article>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { computed, reactive, ref, useSlots, watch } from 'vue';
import { getCommonCustomFieldList, saveCommonCustomFieldList } from '@/api/common';

import RenderColunmNumber from './render-colunm-number.vue';
// 这个页面是动态设置数据列的内容的。
// 用在的地方有: 客群统计的数据概览, 以及群基础数据, 客户群详情的数据概览等....

// 用来判读是否填写了description的插槽
const slots = useSlots();
/* ----------------------------弹窗的显示与隐藏-start---------------------------- */
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
    /** 类型
     * 1-客户群统计数据概览
     * 2-客户群统计群基础数据
     * 3-客户群数据按员工
     * 4-客户群数据按群聊
     * 5-客户群数据按日期
     * 6-客户群详情数据概览
     * */
    type: {
        type: Number,
        default: 1
    },
    /** 最大的长度 */
    length: {
        type: Number,
        default: 6
    },
    /** 最小的长度,默认不使用 */
    isMinLength: {
        type: Boolean,
        default: false
    },
    /** 弹窗标题 */
    title: {
        type: String,
        default: ''
    },
    /** 接口返回的数据外部的处理数据的方法 */
    formatData: {
        type: Function,
        default: undefined
    },
    // Tooltip 组件出现的位置
    placement: {
        type: String,
        default: 'top-start'
    }
});
const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void;
    (e: 'submit'): void;
    (e: 'cancel'): void;
}>();

const visable = computed({
    get() {
        return props.modelValue;
    },
    set(value: boolean) {
        emit('update:modelValue', value);
    }
});

// 打开的情况下设置回显的数据
watch(visable, (newVal: boolean) => {
    if (newVal) {
        isSubmit = false;
        getCustomFieldList();
    }
});
/* ----------------------------弹窗的显示与隐藏-end---------------------------- */

/* ----------------------------列表的渲染-start---------------------------- */
const columnsList = reactive<Array<IColumnsItem>>([]);

/**
 * 是否都不存在 [ '今日新增', '昨日'] 这个值
 */
const isNotAddData = computed(() => {
    return !columnsList.some(
        (item: IColumnsItem) => item.today || item.today === 0 || item.yesterday || item.yesterday === 0
    );
});

const loading = ref(false);
/**
 * 获取数据
 */
const getCustomFieldList = async () => {
    try {
        loading.value = true;
        const res: Array<IColumnsItem> = await getCommonCustomFieldList({
            type: props.type
        });
        const columnsData = await (props.formatData ? props.formatData(res) : res);
        columnsList.length = 0;
        columnsList.push(...columnsData);
        checkColumnsList.value = columnsList.filter(item => item.is_select === 2).map(item => item.field_key);
    } finally {
        loading.value = false;
    }
};

/**
 * 根据后端约定，2的话就是是
 */
const isSure = (value: number) => {
    return value === 2;
};

const computedIsDisabled = (item: IColumnsItem) => {
    // 假如当前选中的规定的数量多，这时候需要用户取消。所以要禁用掉没有选中的
    if (checkColumnsList.value.length > props.length) {
        return isSure(item.is_disable) || !checkColumnsList.value.includes(item.field_key);
    }

    return isSure(item.is_disable);
};
/* ----------------------------列表的渲染-end---------------------------- */
/* ----------------------------选择数据提交-start---------------------------- */

const buttonLoading = ref(false);
const checkColumnsList = ref<string[]>([]);

/**
 * 点击时校验是否超出，并提示
 * @param item 选择的列表项
 */
const checkIsOverFlow = (item: IColumnsItem) => {
    // 如果点击时选中的包含当前的选择项，则显示不提示
    if (checkColumnsList.value.includes(item.field_key)) {
        item.overflowVisable = false;
        return;
    }

    // 如果选中的选择项没有超出最大长度，则显示不提示
    if (checkColumnsList.value.length < props.length) {
        item.overflowVisable = false;
        return;
    }

    item.overflowVisable = true;
};

/** 用来判断窗口关闭时，是否是点击确定的 */
let isSubmit = false;
/**
 * 选择了一些列的内容并提交
 */
const submit = async () => {
    if (props.isMinLength) {
        // 至少选择一个
        if (checkColumnsList.value.length < 1) {
            return ElMessage.warning(`请至少选择1个常用指标`);
        }
    } else if (checkColumnsList.value.length < props.length) {
        return ElMessage.warning(`请选择${props.length}个常用指标`);
    }

    if (checkColumnsList.value.length > props.length) {
        return ElMessage.warning(`仅能选择${props.length}个常用指标`);
    }

    try {
        buttonLoading.value = true;

        // 需要保持抽屉的顺序一致，因此要处理一遍过滤
        const checkList = columnsList
            .filter((item: IColumnsItem) => checkColumnsList.value.includes(item.field_key))
            .map((item: IColumnsItem) => item.field_key);
        await saveCommonCustomFieldList({
            type: props.type,
            field_config: [...checkList]
        });

        emit('update:modelValue', false);
        isSubmit = true;
        emit('submit');
    } finally {
        buttonLoading.value = false;
    }
};

const handleClose = () => {
    emit('update:modelValue', false);
    if (!isSubmit) {
        emit('cancel');
    }
};
/* ----------------------------选择数据提交-end---------------------------- */

/** 选择列的参数类型 */
interface IColumnsItem {
    /** 是否默认选中, 1: 否， 2: 是 */
    is_select: 1 | 2;
    /** 是否默认禁用， 1: 否， 2: 是 */
    is_disable: 1 | 2;
    /** 标题 */
    field_name: string;
    /** 字段对应的key，选中后要传给后端 */
    field_key: string;
    /** 人数。百分比之类的值 */
    field_val: number | string;
    /** 单位, 例如：人，个，%等 */
    unit: string;
    /** 今日新增的数值 */
    today?: number;
    /** 选择超出后的点击提示 */
    overflowVisable?: boolean;
    /** 昨日的数值 */
    yesterday?: number;
}
</script>
<style lang="scss" scoped>
:deep(.select-colunm-dialog) {
    .el-drawer__header {
        padding: 20px 24px;
        font-size: 16px;
        font-family: PingFangSC-Medium, 'PingFang SC';
        font-weight: 500;
        color: #33302d;
        line-height: 16px;
    }

    .el-drawer__body {
        padding: 0;
    }

    .dialog-body {
        overflow-y: auto;
        height: 70vh;
        padding: 24px;
    }

    .select-dialog-icon {
        margin-left: 4px;
        vertical-align: top;
    }

    .column-list {
        margin-top: 16px;
        display: grid;
        grid-template-columns: repeat(3, minmax(240px, 1fr));
        gap: 16px;
    }

    .short-height {
        .column-card {
            height: 96px;
        }
    }

    .column-card {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 126px;
        box-sizing: border-box;
        padding: 16px 24px;
        border-radius: 4px;
        border: 1px solid #eaeaea;
        font-size: 14px;
        font-family: PingFangSC-Regular, 'PingFang SC';
        font-weight: 400;
        user-select: none;

        .column-card-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: #666;
            line-height: 20px;

            .el-checkbox {
                height: auto;
                line-height: normal;
            }
        }

        .column-card-num {
            margin-top: 8px;
            flex: 1;
            font-size: 30px;
            font-family: HelveticaNeue-Medium, HelveticaNeue;
            font-weight: 500;
            color: #33302d;
            line-height: 30px;

            .number {
                cursor: pointer;
            }
        }

        .column-card-units {
            margin-left: 4px;
            font-size: 14px;
            font-family: PingFangSC-Regular, 'PingFang SC';
            font-weight: 400;
            color: #33302d;
            line-height: 20px;
        }

        .column-card-add {
            line-height: 20px;
        }

        .el-checkbox__label {
            display: none;
        }
    }
}
</style>
